/**
 * 基于JSON数组数据循环发送HTTP请求的脚本
 * 根据替换规则将数组中的数据映射到请求参数中
 */

const https = require('https');
const { URL } = require('url');

// 基础请求模板JSON数据
const baseJsonData = {
    "actor": {
        "actorId": "914366e5-453f-474a-834d-1adc92de5b7a",
        "actorName": "283442471@qq.com",
        "actorType": "1",
        "extensions": {
            "studentStatusId": "0e49d131-530a-4ede-9aad-4f668a153cd4",
            "organizationId": "5f8a472d-87c3-4f7e-b5b4-41039760c80f"
        }
    },
    "objectInfo": {
        "objId": "bf0d43fe-78f9-4783-956d-48de6f9dd6b7",
        "objType": "video",
        "objName": "共产主义是社会历史发展的必然.mp4",
        "extensions": {}
    },
    "verbInfo": {
        "verbType": "watched",
        "extensions": {}
    },
    "context": {
        "terminalType": "1",
        "extensions": {
            "courseId": "0746aa7d-1fad-4e95-b996-128cfb7ce7fe",
            "resourcesId": "bf0d43fe-78f9-4783-956d-48de6f9dd6b7",
            "electiveCourseId": "17bbb45b-c98e-4917-a8c6-678e0c92786a",
            "coursewareId": "06e1b143-e95a-4607-be93-e89af98bbc9e",
            "starting_point": "540",
            "ending_point": "583",
            "duration": "60",
            "speed": "",
            "volume": "",
            "clarity": ""
        }
    },
    "result": {},
    "actionTimestamp": "1758612112"
};

// 输入的JSON数组数据 - 你需要替换为实际的数据
const inputJsonArray = [
    {
        "extensionName": "",
        "fileName": "",
        "dataInfo": "",
        "sort": "1",
        "type": "1",
        "ResourceStatus": null,
        "userName": "98a996bc-b376-48bc-bafb-2eeada215c1c",
        "nodeType": 3,
        "resPoints": [],
        "parentId": "b1f0c876-62f6-4c00-be28-7ccd02aa0104",
        "duration": 2669715,
        "fileSize": "",
        "createTime": "Apr 7, 2022 6:12:49 PM",
        "children": [],
        "storgePlatform": 1,
        "subtitle": {
            "total": 0
        },
        "name": "14.第十四课.mp4",
        "id": "41036dbf-e181-4013-adb6-278ce7bcd617",
        "businessType": 0,
        "status": "1",
        "storgeType": 1,
        "fileId": "VEqhkioDATA20220407181222955.mp4"
    },
    {
        "extensionName": "",
        "fileName": "",
        "dataInfo": "",
        "sort": "1",
        "type": "1",
        "ResourceStatus": null,
        "userName": "98a996bc-b376-48bc-bafb-2eeada215c1c",
        "nodeType": 3,
        "resPoints": [],
        "parentId": "b1f0c876-62f6-4c00-be28-7ccd02aa0104",
        "duration": 2829723,
        "fileSize": "",
        "createTime": "Apr 7, 2022 6:13:20 PM",
        "children": [],
        "storgePlatform": 1,
        "subtitle": {
            "total": 0
        },
        "name": "15.第十五课.mp4",
        "id": "1d15ae9e-4e70-4a01-b5ab-314fdbbb3c53",
        "businessType": 0,
        "status": "1",
        "storgeType": 1,
        "fileId": "VEctikyDATA20220407181248923.mp4"
    }
];

/**
 * 根据替换规则处理JSON数据
 * @param {Object} item - 输入数组中的单个对象
 * @returns {Object} - 处理后的JSON数据
 */
function processJsonData(item) {
    // 深度复制基础模板
    const processedData = JSON.parse(JSON.stringify(baseJsonData));
    
    // 替换规则应用
    // objId = id
    processedData.objectInfo.objId = item.id;
    
    // objName = name  
    processedData.objectInfo.objName = item.name;
    
    // resourcesId = id
    processedData.context.extensions.resourcesId = item.id;
    
    // 时长处理
    // duration = duration/1000
    const durationInSeconds = Math.floor(item.duration / 1000);
    processedData.context.extensions.duration = durationInSeconds.toString();
    
    // starting_point = duration - 60
    const startingPoint = Math.max(0, durationInSeconds - 60);
    processedData.context.extensions.starting_point = startingPoint.toString();
    
    // ending_point = duration
    processedData.context.extensions.ending_point = durationInSeconds.toString();
    
    // 更新时间戳为当前时间
    processedData.actionTimestamp = Math.floor(Date.now() / 1000).toString();
    
    return processedData;
}

/**
 * 发送HTTP请求
 * @param {Object} jsonData - 要发送的JSON数据
 * @param {number} index - 当前请求的索引
 * @returns {Promise} - 请求Promise
 */
function sendRequest(jsonData, index) {
    return new Promise((resolve, reject) => {
        // URL编码JSON数据
        const encodedJsonData = encodeURIComponent(JSON.stringify(jsonData));
        const apiUrl = `https://xapi.open.com.cn/api/v1/students/data-collection?jsonData=${encodedJsonData}`;
        
        const url = new URL(apiUrl);
        
        const options = {
            hostname: url.hostname,
            port: 443,
            path: url.pathname + url.search,
            method: 'POST',
            headers: {
                'accept': 'application/json, text/plain, */*',
                'accept-language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7',
                'appkey': '337e8524bfd74f03916512bd7104567f',
                'cache-control': 'no-cache',
                'content-length': '0',
                'origin': 'https://os.open.com.cn',
                'platform': '1',
                'pragma': 'no-cache',
                'priority': 'u=1, i',
                'sec-ch-ua': '"Not;A=Brand";v="99", "Google Chrome";v="139", "Chromium";v="139"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"macOS"',
                'sec-fetch-dest': 'empty',
                'sec-fetch-mode': 'cors',
                'sec-fetch-site': 'same-site',
                'signature': 'dbdcd5e75fc12773172578c3f2759123',
                'signaturenonce': '8666d7ee-408a-4e2f-b924-9869089a53b1',
                'timestamp': new Date().toISOString(),
                'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36'
            }
        };
        
        const req = https.request(options, (res) => {
            let data = '';
            
            res.on('data', (chunk) => {
                data += chunk;
            });
            
            res.on('end', () => {
                console.log(`请求 ${index + 1} 完成:`);
                console.log(`状态码: ${res.statusCode}`);
                console.log(`响应数据: ${data}`);
                console.log('---');
                resolve({ index, statusCode: res.statusCode, data });
            });
        });
        
        req.on('error', (error) => {
            console.error(`请求 ${index + 1} 错误:`, error);
            reject(error);
        });
        
        req.end();
    });
}

/**
 * 主执行函数 - 循环处理数组中的每个项目并发送请求
 */
async function executeRequests() {
    console.log(`开始处理 ${inputJsonArray.length} 个请求...`);
    console.log('===');
    
    for (let i = 0; i < inputJsonArray.length; i++) {
        const item = inputJsonArray[i];
        
        try {
            // 处理JSON数据
            const processedJsonData = processJsonData(item);
            
            console.log(`准备发送请求 ${i + 1}:`);
            console.log(`视频名称: ${item.name}`);
            console.log(`视频ID: ${item.id}`);
            console.log(`时长: ${Math.floor(item.duration / 1000)}秒`);
            
            // 发送请求
            await sendRequest(processedJsonData, i);
            
            // 请求间隔，避免过于频繁
            if (i < inputJsonArray.length - 1) {
                console.log('等待 1 秒后发送下一个请求...');
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
            
        } catch (error) {
            console.error(`处理第 ${i + 1} 个请求时出错:`, error);
        }
    }
    
    console.log('所有请求处理完成!');
}

// 如果直接运行此脚本，则执行请求
if (require.main === module) {
    executeRequests().catch(console.error);
}

// 导出函数供其他模块使用
module.exports = {
    processJsonData,
    sendRequest,
    executeRequests,
    baseJsonData,
    inputJsonArray
};